package com.jx.gn.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jx.gn.config.CommParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.SSLContext;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpClientUtil {
    public static String doGet(String url, Map<String, String> param, Map<String, String> header) {

        // 创建Httpclient对象
        CloseableHttpClient httpclient = createIgnoreSSLHttpClient();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();

            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            RequestConfig config = RequestConfig.custom()
                    .setConnectTimeout(50000)
                    .setSocketTimeout(50000)
                    .build();
            httpGet.setConfig(config);
            //设置请求头部
            if (null != header) {
                for (String key : header.keySet()) {
                    httpGet.addHeader(key, header.get(key));
                }
            }

            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (org.apache.http.conn.ConnectTimeoutException e) {
            // 捕获超时异常 并反馈给调用者
//			e.printStackTrace();
            return "connection time out";
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

    public static String doGet(String url) {
        return doGet(url, null, null);
    }
    public static String doGetHeard(String url) {
        Map<String ,String> map = new HashMap<>(1);
        map.put("access-token",getAccessToken());
        return doGet(url, null, map);
    }

    public static String doPost(String url, Map<String, String> param, Map<String, String> header) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建参数列表
            if (param != null) {
                List<NameValuePair> paramList = new ArrayList<>();
                for (String key : param.keySet()) {
                    paramList.add(new BasicNameValuePair(key, param.get(key)));
                }
                // 模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
                // 设置请求头部
                if (null != header && header.isEmpty()) {
                    for (String key : header.keySet()) {
                        httpPost.addHeader(key, header.get(key));
                    }
                }

            }
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static CloseableHttpClient createIgnoreSSLHttpClient() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain,
                                         String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 豆豆上传文件
     *
     * @param url  http://vrv.linkdood.cn/platform/api2/resource/upload?type=type
     * @param file
     * @param type 1缩略图、2图片、3语音、4视频、6文件
     * @return
     */
    public static String doPostFile(String url, File file, String type)  {
//        System.setProperty("jsse.enableSNIExtension", "false");


        // 创建Httpclient对象
//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = createIgnoreSSLHttpClient();
        CloseableHttpResponse response = null;
        String resultString = "";
        MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();

        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url+"?type="+type);
            // 创建参数列表

            multipartEntityBuilder.addBinaryBody("file", new FileInputStream(file),ContentType.MULTIPART_FORM_DATA,file.getName());
//            multipartEntityBuilder.addPart("type", new StringBody(type,ContentType.create("text/plain", Consts.UTF_8)));
            HttpEntity httpEntity = multipartEntityBuilder.build();

            httpPost.setEntity(httpEntity);

            httpPost.addHeader("access-token", getAccessToken());


            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            log.error("网络请求异常 {}", e);
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    public static String doPost(String url) {
        return doPost(url, null, null);
    }

    public static String doPostJson(String url, String json) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = createIgnoreSSLHttpClient();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("access-token", getAccessToken());
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);

            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }

    private static String getAccessToken() {
        String key = "accessToken";
        LocalCache cache = LocalCache.getInstance();
        String accessToken = (String) cache.get(key);
        if (StrUtil.isBlank(accessToken)) {
            String str = doGet("https://gahl2.linkdood.cn:10669/platform/api2/token?accessType=CLIENT&appID=21256822787&appSecret=qA-W68hbzn3eqmm7SEAVk0T3ldpVykgtEqeSxXl_ycs");
            JSONObject json = JSONUtil.parseObj(str);
            if (json.getInt("code") == 0) {
                JSONObject result = json.getJSONObject("result");
                String access_token = result.getStr("access_token");
                accessToken = access_token;
                cache.set(key, access_token, 7200 * 1000);
            }

        }
        return accessToken;
//        cache.set(key, accessToken, 7200*1000);

    }


    public static void main(String[] args) {
        String s = HttpClientUtil.doGetHeard("https://gahl2.linkdood.cn:10669"+ CommParams.GET_USER_INFO+"test01?lang=zh_CN");
        System.out.println("https://gahl2.linkdood.cn:10669"+ CommParams.GET_USER_INFO+"test01?lang=zh_CN");
        System.out.println(s);
    }



}
